<?php
namespace app\api\controller;
use app\BaseController;
use EasyAdmin\upload\Uploadfile;

class Upload extends BaseController
{
    function upload_field(){
        $data = [
            'upload_type' => $this->request->post('upload_type'),
            'file'        => $this->request->file('file'),
        ];
        $uploadConfig = sysconfig('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        $rule = [
            'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
            'file|文件'              => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->validate($data, $rule);
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
        } catch (\Exception $e) {
//            $this->error($e->getMessage());
            return api_fail($e->getMessage());
        }
        if ($upload['save'] == true) {
            return api_success($upload['msg'],['url' => $upload['url']]);
//            $this->success($upload['msg'], ['url' => $upload['url']]);
        } else {
            return api_fail($upload['msg']);
//            $this->error($upload['msg']);
        }
    }
}